import { Context } from 'koa';
const NXlSX = require("node-xlsx");
const fs = require('fs')
const { getEnts, getEntsByPage, getByname, getBynameandPage, getEntsById, createEnt, update, delEnt, importEnts } = require('../service/ents.service')
const { isEmpty, invalidVideoId } = require('../constants/err.type')

interface pageInfo {
    pageNum?: number,
    pageSize?: number
}

class EntController {
    private entObj: Map<string, string>;
    constructor() {
        this.entObj = new Map([
            ['id', 'id'],
            ['企业名称', 'name'],
            ['企业简称', 'sname'],
            ['地址', 'address'],
            ['省', 'province_name'],
            ['市', 'city'],
            ['创建时间', 'creattime'],
            ['修改时间', 'moditime'],
            ['统一信用编号', 'uscc'],
            ['介绍', 'introduction'],
        ]);
    }

    // 获取企业列表接口
    public async getEnts(ctx: Context) {
        try {
            let res: any = null;
            let { pageNum, pageSize }: pageInfo = ctx.query;
            if (pageNum && pageSize) {
                pageNum = Math.max(pageNum * 1, 1);
                pageSize = Math.max(pageSize * 1, 1);
                res = await getEntsByPage(pageNum, pageSize);
            } else {
                res = await getEnts();
            }
            ctx.body = {
                code: 200,
                message: '获取企业列表成功',
                result: {
                    ...res
                }
            }
        } catch (error) {
            console.error('获取企业列表失败', error)
        }
    }
    // 根据关键词获取企业
    public async getEntsByname(ctx: Context) {
        try {
            let res: any = null;
            let { pageNum, pageSize }: pageInfo = ctx.query;
            const name = ctx.query.name
            if (!name) return ctx.app.emit('error', isEmpty, ctx)
            if (pageNum && pageSize) {
                pageNum = Math.max(pageNum * 1, 1);
                pageSize = Math.max(pageSize * 1, 1);
                res = await getBynameandPage(pageNum, pageSize, name);
            } else {
                res = await getByname(name);
            }
            ctx.body = {
                code: 200,
                message: '搜索企业类型列表成功',
                result: {
                    ...res
                }
            }
        } catch (error) {
            console.error('根据关键词获取企业类型列表失败', error)
        }
    }
    // 根据id获取企业
    public async getById(ctx: Context) {
        try {
            const id = ctx.params.id
            const res: any = await getEntsById(id);
            if (res) {
                ctx.body = {
                    code: 200,
                    message: '根据id获取企业成功',
                    result: res
                }
            } else {
                return ctx.app.emit('error', invalidVideoId, ctx)
            }
        } catch (error) {
            console.error('根据id获取企业失败', error)
        }
    }
    // 添加企业
    public async addEnt(ctx: Context) {
        try {
            const res = await createEnt(ctx.request.body)
            if (res) {
                ctx.body = {
                    code: 200,
                    message: `添加企业成功`,
                    id: res.id
                }
            } else {
                ctx.body = {
                    code: 500,
                    message: `添加企业失败`
                }
            }
        } catch (error) {
            console.error('添加企业失败', error)
        }
    }
    // 更新企业
    public async updateEnt(ctx: Context) {
        try {
            const id = ctx.params.id
            const res = await update(id, ctx.request.body)
            if (res) {
                ctx.body = {
                    code: 200,
                    message: `更新企业成功`
                }
            } else {
                ctx.body = {
                    code: 500,
                    message: `更新企业失败`
                }
            }
        } catch (error) {
            console.error('更新企业', error)
        }
    }
    // 删除企业
    public async deleteEnt(ctx: Context) {
        try {
            const id = ctx.params.id
            const res = await delEnt(id)
            if (res) {
                ctx.body = {
                    code: 200,
                    message: `删除企业成功`
                }
            } else {
                ctx.body = {
                    code: 500,
                    message: `删除企业失败`
                }
            }
        } catch (error) {
            console.error('更新企业失败', error)
        }
    }
    // 导出企业信息为Excel
    public async exportExcel(ctx: Context) {
        try {
            // 表头
            const _headers = ['id', '企业名称', '企业简称', '地址', "城市代码", "省", "市", "创建时间", "修改时间", "统一信用编号", "介绍"];
            //表格数据
            const entsData = await getEnts()
            const _data = entsData.rows
            // console.log(_data)
            let data = [];
            for (let i = 0; i < _data.length; i++) {
                let arr = [];
                for (let key in _data[i].dataValues) {
                    arr.push(_data[i].dataValues[key])
                }
                data.push(arr);
            }
            data.unshift(_headers);
            // 数据格式为[["hello","223"],["22","23"]];
            let buffer = NXlSX.build([{ name: "sheetName", data: data }]);
            // 返回buffer流到前端
            ctx.body = buffer
        } catch (error) {
            console.error('导出企业失败', error)
        }
    }
    // 导入Excel
    public async importExcel(ctx: Context) {
        const ent = new EntController()
        const file: any = ctx.request.files.file;
        const obj = NXlSX.parse(file.path)
        const excelObj = obj[0].data
        const insertData = []; //存放数据
        //导入解析成功后 将文件删除
        fs.unlink(file.path, function (err) {
            if (err) throw err;
        })
        for (let i = 1; i < excelObj.length; i++) {
            const data = excelObj[i];
            const EntObj = new Object();
            for (let j = 0; j < data.length; j++) {
                if(excelObj[0][j] == 'id') continue
                const key = ent.entObj.get(excelObj[0][j])
                EntObj[key] = data[j]
            }
            insertData.push(EntObj)
        }
        const res = await importEnts(insertData)
        if(res) {
            ctx.body = {
                code: 200,
                message: `导入信息成功`
            }
        } else {
            ctx.body = {
                code: 500,
                message: `导入信息失败`
            }
        }
    }
}

module.exports = new EntController();